import SwiftUI

struct AnimationGradientViews: View {
    var letters: String // 要偏移的字母
    var offsetAmount: CGFloat // 偏移量
    var delayBetweenAnimations: Double // 每个字符之间的动画延迟
    var animationDuration: Double // 每个字母的动画持续时间
    var shouldLoop: Bool // 是否循环动画
    var colors: [Color] // 变化的颜色数组
    
    @State private var offsets: [CGFloat] // 用于跟踪每个字母的偏移量
    @State private var currentColors: [Color] // 当前显示的颜色
    
    // 添加所有默认值
    init(
        letters: String = "abcdefgh",
        offsetAmount: CGFloat = 50,
        delayBetweenAnimations: Double = 0.5,
        animationDuration: Double = 1.5,
        shouldLoop: Bool = true,
        colors: [Color] = [.red, .green, .blue, .orange, .purple]
    ) {
        self.letters = letters
        self.offsetAmount = offsetAmount
        self.delayBetweenAnimations = delayBetweenAnimations
        self.animationDuration = animationDuration
        self.shouldLoop = shouldLoop
        self.colors = colors
        self._offsets = State(initialValue: Array(repeating: 0, count: letters.count))
        self._currentColors = State(initialValue: Array(repeating: colors.first ?? .black, count: letters.count))
    }
    
    var body: some View {
        VStack {
            HStack {
                ForEach(0..<letters.count, id: \.self) { index in
                    Text(String(letters[letters.index(letters.startIndex, offsetBy: index)]))
                        .font(.largeTitle)
                        .offset(y: offsets[index])
                        .foregroundColor(currentColors[index]) // 使用当前颜色
                }
            }
            .onAppear {
                startAnimation()
            }
            
            Button(action: {
                resetAnimation()
            }) {
                Text("重新开始动画")
                    .padding()
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(8)
            }
        }
    }
    
    private func startAnimation() {
        // 使用动画将每个字母向上移动指定的偏移量
        for index in offsets.indices {
            let delay = delayBetweenAnimations * Double(index) // 计算每个字母的延迟
            
            // 向上移动动画
            withAnimation(Animation.easeInOut(duration: animationDuration).delay(delay)) {
                offsets[index] = -offsetAmount // 向上移动指定的偏移量
            }
            
            // 在动画过程中平滑地切换颜色
            DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
                let colorAnimation = Animation.linear(duration: animationDuration)
                withAnimation(colorAnimation) {
                    let availableColors = Array(colors.dropFirst())
                                      currentColors[index] = availableColors.randomElement() ?? colors.last! // 随机选择排除第0个的颜色
                }
            }
            
            // 立即开始返回到初始位置的动画，并在完成后恢复初始颜色
            DispatchQueue.main.asyncAfter(deadline: .now() + animationDuration + delay) {
                withAnimation(Animation.easeInOut(duration: animationDuration)) {
                    offsets[index] = 0 // 返回到初始位置
                    currentColors[index] = colors.first ?? .black // 恢复到初始颜色
                }
                
                // 如果是最后一个字母，重置动画并暂停 1 秒后重新开始（如果 shouldLoop 为 true）
                if index == offsets.count - 1 && shouldLoop {
                    DispatchQueue.main.asyncAfter(deadline: .now() + animationDuration) {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                            resetAnimation() // 动画完成后重新开始
                        }
                    }
                }
            }
        }
    }
    
    private func resetAnimation() {
        // 重置动画并重新开始
        offsets = Array(repeating: 0, count: letters.count)
        currentColors = Array(repeating: colors.first ?? .black, count: letters.count) // 重置颜色
        startAnimation()
    }
}
